package com.es.text;

import com.es.dao.ProductDao;
import com.es.pojo.Product;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:左泽林
 * @date:日期:2021-08-30-时间:11:05
 * @message:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESProductDaoTest {
    @Autowired
    private ProductDao productDao;

    @Test
    public void save(){
        /*新增*/
        Product product = new Product();
        product.setId(3L);
        product.setTitle("华为手机");
        product.setCategory("手机");
        product.setPrice(2999.0);
        product.setImages("存放的图片地址");
        productDao.save(product);
    }


    @Test
    public void update(){
        /*新增*/
        Product product = new Product();
        product.setId(2L);
        product.setTitle("小米手机");
        product.setCategory("手机");
        product.setPrice(2899.0);
        product.setImages("存放的图片地址");
        productDao.save(product);
    }


    @Test
    public void findById(){
        /*根据id查询*/
        Product product = productDao.findById(2L).get();
        System.out.println(product);
    }

    @Test
    public void findAll(){
        Iterable<Product> all = productDao.findAll();
        for (Product product : all) {
            System.out.println(product);
        }
    }

    @Test
    public void delete(){
        Product product = new Product();
        product.setId(2L);
        productDao.delete(product);
    }


    @Test
    public void saveAll(){
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            Product product = new Product();
            product.setId(Long.valueOf(i));
            product.setTitle("小米手机"+i);
            product.setCategory("手机");
            product.setPrice(2899.0*i);
            product.setImages("存放的图片地址"+i);
            productList.add(product);
        }

        productDao.saveAll(productList);
    }


    //分页查询
    @Test
    public void findByPageable(){
        //设置排序（排序方式，正序还是倒叙，排序id）
        Sort id = Sort.by(Sort.Direction.DESC, "id");

        int currentPage=0; //当前页，第一页从0开始，1表示第二页
        int pageSize = 5 ; //每页显示多少条

        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize, id);

        //分页查询
        Page<Product> all = productDao.findAll(pageRequest);

        /*for (Product product : all.getContent()) {
            System.out.println(product);
        }*/

        for (Product product : all) {
            System.out.println(product);
        }

    }




}
